package com.czh.circle.server.config.interceptor;

import com.czh.circle.api.constants.UserConstant;
import com.czh.circle.server.config.context.LoginContextHolder;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


/**
 * 登录拦截器
 *
 * @author: ChickenWing
 * @date: 2023/11/26
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader(UserConstant.USER_CONTEXT_ID);
        if (StringUtils.isNotBlank(userId)) {
            LoginContextHolder.set(UserConstant.USER_CONTEXT_ID, userId);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginContextHolder.remove();
    }
}
